Skip to main content

Exception Handling

1. Try Except

When an error occurs in a program, it usually causes the program to crash.

result = 10 / 0 # ZeroDivisionError: division by zero

print("This will not be printed.")

To handle these errors and prevent the program from crashing, we can use the try except blocks.

try block is similar to an if-else statement. The code inside a try block is always executed, but if any line of code raises an error, the program will immediately jump to the except block. If no error occurs, the except block is skipped.

This is called exception handling.

try:
# code that might cause an error
result = 10 / 0
except:
print("An error occurred!")

print("This will be printed regardless.")

The try/except blocks have their own scope in Python, similar to other block structures like functions and loops. So a variable declared in the the block is local to only that block.

2. Error Catching

When an error occurs in a try block, it may be useful for us to know exactly what error occurred. This can allow us to better debug our code.

Example: The code will catch the error and place it inside a variable called error using the as keyword. We can then print this variable to see the error message, which would be:

try:
result = 10 / 0
except Exception as error:
print("Error:", error)
Error: division by zero

3. Multiple Except Blocks

Instead of having a single except block to handle all exceptions,

try:
n = 10 / 0
except Exception as error:
print("An error occurred:", error)

We can have multiple except blocks to handle different types of exceptions.

  • The first except will catch a ValueError
  • The second will catch a ZeroDivisionError
  • The third will catch any other exceptions. If neither a ValueError nor a ZeroDivisionError occurs, the third block will still catch all other exceptions.
try:
num1 = int(a)
num2 = int(b)
result = num1 / num2
except ValueError:
print("Error: Invalid value!")
except ZeroDivisionError:
print("Error: Division by zero!")
except Exception as error:
print("An error occurred:", error)

There are many built-in exceptions in Python. Some common ones include TypeErrorIndexErrorKeyErrorFileNotFoundError, and ImportError. You can also create your own exceptions. A list of built-in exceptions can be found in the Python documentation.